package com.liang.circle.server.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.alibaba.druid.support.json.JSONUtils;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liang.circle.api.common.PageDTO;
import com.liang.circle.api.common.PageQuery;
import com.liang.circle.api.req.ShareMomentGetReq;
import com.liang.circle.api.req.ShareMomentSaveReq;
import com.liang.circle.api.vo.ShareMomentVO;
import com.liang.circle.server.entity.po.ShareCommentReply;
import com.liang.circle.server.entity.po.ShareMoment;
import com.liang.circle.server.mapper.ShareCommentReplyMapper;
import com.liang.circle.server.mapper.ShareMomentMapper;
import com.liang.circle.server.service.ShareCommentReplyService;
import com.liang.circle.server.service.ShareMomentService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
public class ShareMomentServiceImpl extends ServiceImpl<ShareMomentMapper, ShareMoment> implements ShareMomentService {

    private final ShareCommentReplyMapper shareCommentReplyMapper;

    @Override
    public void saveMoment(ShareMomentSaveReq requestParam) {
        ShareMoment shareMoment = BeanUtil.copyProperties(requestParam, ShareMoment.class);
        shareMoment.setReplyCount(0);
        if (requestParam.getPicUrlList() != null) {
            shareMoment.setPicUrls(JSONUtils.toJSONString(requestParam.getPicUrlList()));
        }
        save(shareMoment);
    }

    @Override
    public PageDTO<ShareMomentVO> getMomentList(ShareMomentGetReq requestParam) {
        PageQuery pageQuery = requestParam.getPageQuery();
        Page<ShareMoment> page = pageQuery.toMpPage();
        Page<ShareMoment> res = lambdaQuery()
                .eq(ShareMoment::getCircleId, requestParam.getCircleId())
                .orderByDesc(ShareMoment::getCreatedTime)
                .page(page);
        return PageDTO.of(res, item -> BeanUtil.copyProperties(item, ShareMomentVO.class));
    }

    @Override
    public void removeMoment(Long id) {
        // 某一条动态删除，则该动态下的所有回复均删除
        UpdateWrapper<ShareCommentReply> wrapper = new UpdateWrapper<ShareCommentReply>()
                .eq("moment_id", id)
                .set("is_deleted", 1);
        shareCommentReplyMapper.delete(wrapper);
        removeById(id);
    }

    @Override
    public void updateMoment(ShareMoment requestParam, int count) {
        lambdaUpdate()
                .eq(ShareMoment::getId, requestParam.getId())
                .setSql("reply_count = reply_count + " + count)
                .update();
    }
}




